package com.nononsenseapps.feeder.model

import android.app.Application
import androidx.fragment.app.Fragment
import androidx.lifecycle.*
import androidx.lifecycle.viewmodel.CreationExtras
import com.nononsenseapps.feeder.db.entity.Feed
import com.nononsenseapps.feeder.db.room.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext

class FeedViewModel(application: Application,private val state: SavedStateHandle) : AndroidViewModel(application) {
    private val feedDao = AppDatabase.getInstance(application).feedDao()

    fun loadFeed(feedId: Long):Feed = runBlocking(Dispatchers.IO) {
        feedDao.loadLiveFeed(feedId)
    }

     fun deleteFeed(feedId: Long)=viewModelScope.launch(Dispatchers.IO){
        feedDao.deleteFeed(Feed(feedId))
    }

    fun markAsNotified(feedId:Long,feedTag:String?,on:Boolean)= viewModelScope.launch(Dispatchers.IO){
        when {
            feedId > ID_UNSET -> feedDao.setNotify(feedId, on)
            feedId == ID_ALL_FEEDS -> feedDao.setAllNotify(on)
            feedId == FAVORITE_FEED_ID -> feedDao.setNotify(feedId, on)
            feedTag?.isNotEmpty() == true -> feedDao.setNotify(feedTag, on)
        }
    }

    fun changeFeedAttentionLevel(id: Long, level: Int) = viewModelScope.launch(Dispatchers.IO){
        feedDao.changeFeedAttentionLevel(id,level)
    }

    fun getFeedLastOpenTreeName(feedId: Long):String = runBlocking(Dispatchers.IO) {
        feedDao.findFeedViewListTypeTreeName(feedId)
    }
}

/*class FeedViewModelFactory : ViewModelProvider.NewInstanceFactory() {
    override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
        val application = checkNotNull(extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY])
        return FeedViewModel(application,extras.createSavedStateHandle()) as T
    }
}

fun Fragment.getFeedViewModel(): FeedViewModel {
    return ViewModelProvider(this,FeedViewModelFactory()).get(FeedViewModel::class.java)
}*/
